<template>
    <div style="background-color: #fff; padding: 20px;">
        <el-form ref="formRef" :model="form" label-width="120px">
            <el-form-item label="商品名：">
                <el-input v-model="form.goods_name" style="width: 600px;"></el-input>
            </el-form-item>
            <el-form-item label="市场价：">
                <el-input-number v-model="form.market_price" :precision="2" :min="0.01" :max="100000000" @change="priceChange" />
<!--                <el-input v-model="form.market_price"></el-input>-->
            </el-form-item>
            <el-form-item label="实际售价：">
                <el-input-number v-model="form.goods_price" :precision="2" :min="0.01" :max="100000000" @change="priceChange" />
<!--                <el-input v-model="form.goods_price"></el-input>-->
            </el-form-item>

            <el-form-item label="封面图：" class="fm">
<!--                <el-upload-->
<!--                        :action="action"-->
<!--                        :http-request="upGoodsImg"-->
<!--                        :auto-upload="true"-->
<!--                        method="patch"-->
<!--                        ref="uploadAvatar"-->
<!--                        :on-change="handleChangeImg"-->
<!--                        :with-credentials="true"-->
<!--                        name="corpimgfile"-->
<!--                        :show-file-list="false"-->
<!--                >-->
                <el-upload
                        :action="action"
                        :http-request="upGoodsImg"
                        :on-change="handleChangeImg"
                        :with-credentials="true"
                        :show-file-list="false"
                >
                    <div>
                        <el-avatar :size="100" shape="square" :src="form.imgurl"></el-avatar>
                        <div class="img-change">更换</div>
                    </div>
                </el-upload>
<!--                <el-input v-model="form.goods_img"></el-input>-->

            </el-form-item>
            <el-form-item label="关联商品图片：" v-if="isImgList">
                <el-upload
                        class="upload-demo"
                        :action="action"
                        :http-request="upGoodsImgList"
                        :file-list="form.goodsimglist"
                        :limit=10
                        :on-exceed="exceed"
                        :show-file-list="false"
                >
                    <el-button type="primary">上传图片</el-button>
                    <template #tip>
                        <div class="el-upload__text">
                            建议上传图片比例为1:1，尺寸为720，否则可能出现变形
                        </div>
                    </template>

                </el-upload>
                <ul class="imglist">
                    <li :key="i" v-for="(item,i) in form.goodsimglist">
                        <el-image :src=item.url  fit="scale-down" style="width:160px;height:160px"></el-image>
                        <a class="delete-image" href="javascript:;" @click="removeImg(i)">
                            <el-icon><circle-close/></el-icon>
                        </a>
                    </li>
                </ul>
            </el-form-item>
            <el-form-item label="关联详情图片：" v-if="isImgList">
                <el-upload
                        class="upload-demo"
                        :action="action"
                        :http-request="upContentImgList"
                        :limit=10
                        :on-exceed="exceed1"
                        :show-file-list="false"
                >
                    <el-button type="primary">上传图片</el-button>
                    <template #tip>
                        <div class="el-upload__text">
<!--                            建议上传图片比例为1:1，尺寸为720，否则可能出现变形-->
                        </div>
                    </template>

                </el-upload>
                <ul class="imglist">
                    <li :key="i" v-for="(item,i) in form.contentimglist">
                        <el-image :src=item.url  fit="scale-down" style="width:160px;height:160px"></el-image>
                        <a class="delete-image" href="javascript:;" @click="removeImg1(i)">
                            <el-icon><circle-close/></el-icon>
                        </a>
                    </li>
                </ul>
            </el-form-item>

            <el-form-item label="商品货号：">
                <el-input v-model="form.goods_sn" style="width: 600px;"></el-input>
            </el-form-item>
            <el-form-item label="商品状态：">
<!--                <el-input v-model="form.state"></el-input>-->
                <el-radio-group v-model="form.state">
                    <el-radio  :label="1" border>上架</el-radio>
                    <el-radio  :label="0" border>下架</el-radio>
                </el-radio-group>
            </el-form-item>
            <el-form-item label="商品描述：">
                <el-input v-model="form.goods_desc" style="width: 600px;"></el-input>
            </el-form-item>
            <el-form-item label="供应商：">
                <el-input v-model="form.supplier" style="width: 600px;"></el-input>
            </el-form-item>
            <el-form-item label="来源方：">
                <el-select v-model="form.source" class="m-2" placeholder="Select" size="large">
                    <el-option
                            v-for="item in sourceArr"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                    />
                </el-select>
            </el-form-item>
            <el-form-item label="来源方url：">
                <el-input v-model="form.sourceurl" style="width: 600px;"></el-input>
            </el-form-item>
            <el-form-item label="商品介绍：">

                <!--            <wangeditor v-model="form.content" :isClear="isClear" @change="change"></wangeditor>-->
                <div v-if="isEditorShow" style="border: 1px solid #ccc">
                    <Toolbar
                            :editorId="editorId"
                            :defaultConfig="toolbarConfig"
                            :mode="mode"
                            style="border-bottom: 1px solid #ccc;"
                    />
                    <Editor
                            :editorId="editorId"
                            :defaultConfig="editorConfig"
                            :defaultHtml="getDefaultContent"
                            :mode="mode"
                            style="height: 500px"
                    />
                </div>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="onSubmit()">提交</el-button>
<!--                <el-button type="primary" @click="gettool()">tool</el-button>-->
            </el-form-item>
        </el-form>
    </div>
</template>

<script setup>
    import { reactive,ref,computed,onBeforeUnmount } from 'vue'
    import cloneDeep from 'lodash.clonedeep'
    import {useStore} from "vuex";
    import {getCreateGoods,getUpdateGoods,getGoodsInfoApi,getUpImg} from "@/api/goods/goods";
    import {ElMessage} from "element-plus";
    import {useRoute, useRouter} from 'vue-router'
    import { Editor, Toolbar, getEditor, removeEditor } from '@wangeditor/editor-for-vue'

    const $route = useRoute()
    const $router = useRouter()
    const store = useStore()
    const corpinfo = store.getters.corpinfo
    // do not use same name with ref
    const goods_id = ref(0)
    const action = ref(process.env.VUE_APP_BASE_API + '/mall/goods/upImg')
    // const action = ref('http://10.168.60.233:8002/api/mall/goods/upImg')
    const form = reactive({
        corpid:corpinfo.corpid,
        goods_name: '',
        market_price: 0,
        goods_price: 0,
        goods_sn: '',
        goods_img: '',
        imgurl:'',
        state: 1,
        goods_desc: '',
        supplier: '',
        content:'',
        source: 1,
        sourceurl: '',
        goodsimglist: [],
        contentimglist: [],
        // imglist: [],
    })
    const sourceArr = [
        {
            value: 1,
            label: '自有',
        },
        {
            value: 2,
            label: '淘宝',
        },
    ]
    const isfidlist = ref(0)
    const iscontentlist = ref(0)

    //--- wangeditor -- start

    const isImgList = ref(false)
    const isEditorShow = ref(false)
    const mode = ref('default');
    const editorConfig = { placeholder: '请输入内容...',MENU_CONF: {} }
    editorConfig.MENU_CONF['uploadImage'] = {
        server: process.env.VUE_APP_BASE_API + '/mall/goods/upImgWang',
        // server: 'http://10.168.60.233:8002/api/mall/goods/upImgWang',
        meta: {
            corpid: corpinfo.corpid,
        },
        fieldName:'upimg',
        onError(file,err) {
            if(file.size > 2097151){
                alert('图片尺寸不能超过2M')
                return;
            }else {
                alert(err.message)
            }

        },
    }
    const editorId = `w-e-${Math.random().toString().slice(-5)}` //【注意】编辑器 id ，要全局唯一

    const defaultHtml = ref('')

    const getDefaultContent = computed(() => cloneDeep(defaultHtml.value))

    // 组件销毁时，也及时销毁编辑器
    onBeforeUnmount(() => {
        const editor = getEditor(editorId)
        if (editor == null) return

        editor.destroy()
        removeEditor(editorId)
    })

    const toolbarConfig = reactive({
        toolbarKeys: [
            // 菜单 key
            'headerSelect',
            // 分割线
            '|',
            // 菜单 key
            'bold', 'italic',
            'uploadImage','color','fontSize','fontFamily',
            {
                key: '"group-justify"', // 必填，要以 group 开头
                title: '对齐', // 必填
                iconSvg: '<svg viewBox="0 0 1024 1024"><path d="M768 793.6v102.4H51.2v-102.4h716.8z m204.8-230.4v102.4H51.2v-102.4h921.6z m-204.8-230.4v102.4H51.2v-102.4h716.8zM972.8 102.4v102.4H51.2V102.4h921.6z"></path></svg>', // 可选
                menuKeys: ['justifyLeft', 'justifyRight', 'justifyCenter', 'justifyJustify'] // 下级菜单 key ，必填
            },

        ]
    })
    // 查看工具栏有哪些选项
    // import { DomEditor } from '@wangeditor/editor'
    // const gettool = () => {
    //     const editor = getEditor(editorId)
    //     const toolbar = DomEditor.getToolbar(editor)
    //     // const menu = editor.getAllMenuKeys()
    //     const bar = toolbar.getConfig().toolbarKeys
    //     console.log(bar);
    // }

    //--- wangeditor -- end

    //查询商品详情
    const getGoods = () => {
        let queryList = {
            goods_id : goods_id.value
        }
        getGoodsInfoApi(queryList).then(res => {
            if (res.errcode == 0) {
                form.goods_name = res.data.goods_name;
                form.market_price = parseInt(res.data.market_price);
                form.goods_price = parseInt(res.data.goods_price);
                form.goods_sn = res.data.goods_sn;
                form.goods_img = res.data.goods_img;
                form.imgurl = res.data.imgurl_150;
                form.state = res.data.state;
                form.goods_desc = res.data.goods_desc;
                form.supplier = res.data.supplier;
                form.source = res.data.source;
                form.sourceurl = res.data.sourceurl;
                defaultHtml.value = res.data.content
                for(let i=0;i<res.data.imglist.length;i++){
                    if(res.data.imglist[i]['imgtype'] == 0) {
                        form.goodsimglist.push({
                            'name': res.data.imglist[i]['fid'],
                            'url': res.data.imglist[i]['url_720'],
                            'width': res.data.imglist[i]['width'],
                            'height': res.data.imglist[i]['height'],
                            'imgtype': res.data.imglist[i]['imgtype']
                        })
                    }
                    if(res.data.imglist[i]['imgtype'] == 1) {
                        form.contentimglist.push({
                            'name': res.data.imglist[i]['fid'],
                            'url': res.data.imglist[i]['url_720'],
                            'width': res.data.imglist[i]['width'],
                            'height': res.data.imglist[i]['height'],
                            'imgtype': res.data.imglist[i]['imgtype']
                        })
                    }
                }
                isEditorShow.value = true
                console.log(form.goodsimglist);
            } else {
                ElMessage.error('发生错误，稍后再试！')
            }
        })
    }
    if ($route.query.goods_id){
        goods_id.value = $route.query.goods_id;
        //取商品详情
        getGoods()
    }else{
        isEditorShow.value = true
    }
    //提交
    const onSubmit = () => {
        if (form.goods_name == '') {
            ElMessage({
                message: '请输入商品名',
                type: 'warning',
            })
            return;
        }
        const editor = getEditor(editorId)
        form.content = editor.getHtml()
        if (goods_id.value == 0) {
            Create()
        } else {
            Update()
        }

    }

    //创建商品
    const Create = () => {
        let queryList = form
        // console.log(queryList);
        getCreateGoods(queryList).then(res => {
            if (res.errcode == 0) {
                ElMessage.success('操作成功')
                $router.push('/goods/index');
            } else {
                ElMessage.error('发生错误，稍后再试！')
            }
        })
    }
    //修改商品
    const Update = () => {
        let queryList = form
        queryList['goods_id'] = goods_id.value

        //没修改过关联图片，则从数组中删除，否则数据库会更新
        if(isfidlist.value == 0){
            delete queryList['goodsimglist'];
        }
        if(iscontentlist.value == 0){
            delete queryList['contentimglist'];
        }
        getUpdateGoods(queryList).then(res => {
            if (res.errcode == 0) {
                ElMessage.success('操作成功')
                $router.push('/goods/index');
            } else {
                ElMessage.error('发生错误，稍后再试！')
            }
        })
    }
    const priceChange = (value) => {
        console.log(value)
    }
    //图片上传
    const handleChangeImg = (file) => {
        form.imgurl = URL.createObjectURL(file.raw)
    }
    //封面图
    const upGoodsImg = (params) => {
        // console.log(params);
        const formData = new FormData()
        formData.append('corpimgfile', params.file)
        formData.append('corpid', form.corpid)
        getUpImg(formData).then(response => {
            if (response.errcode == 0) {
                form.goods_img = response.data.fid
                ElMessage({type: 'success', message: 'success', duration: 2000})
            }
        })
    }
    // const upimgsuccess = (response, file, fileList) => {
    //     console.log(response);
    // }
    //关联商品图片
    const upGoodsImgList = (params) => {
        console.log(params);
        const formData = new FormData()
        formData.append('corpimgfile', params.file)
        formData.append('corpid', form.corpid)
        getUpImg(formData).then(response => {
            if (response.errcode == 0) {
                isfidlist.value = 1
                // form.fidlist.push(response.data.fid)
                form.goodsimglist.push({'name':response.data.fid,'url':response.data.url,'width':response.data.width,'height':response.data.height,'imgtype':0})
                ElMessage({type: 'success', message: 'success', duration: 2000})
            }
        })
    }
    //删除关联商品图片
    const removeImg = (idx) =>{
        isfidlist.value = 1
        // form.fidlist.splice(idx,1);
        form.goodsimglist.splice(idx,1);
        // console.log(form.fidlist);
        console.log(form.imglist);
        return false
    }

    //关联详情图片
    const upContentImgList = (params) => {
        console.log(params);
        const formData = new FormData()
        formData.append('corpimgfile', params.file)
        formData.append('corpid', form.corpid)
        getUpImg(formData).then(response => {
            if (response.errcode == 0) {
                iscontentlist.value = 1
                // form.fidlist.push(response.data.fid)
                form.contentimglist.push({'name':response.data.fid,'url':response.data.url,'width':response.data.width,'height':response.data.height,'imgtype':1})
                ElMessage({type: 'success', message: 'success', duration: 2000})
            }
        })
    }
    //删除关联详情图片
    const removeImg1 = (idx) =>{
        iscontentlist.value = 1
        // form.fidlist.splice(idx,1);
        form.contentimglist.splice(idx,1);
        // console.log(form.fidlist);

        return false
    }
    const exceed = () =>{
        alert('最多关联10张图片');
        return false
    }
    const exceed1 = () =>{
        alert('最多关联10张图片');
        return false
    }


</script>
<style src="@wangeditor/editor/dist/css/style.css"></style>
<style scoped lang="scss">
    .imglist{
    display: flex;
    flex-wrap: wrap;
    li {
      position: relative;
      width: 160px;
      line-height:initial;
      margin-right: 15px;
      margin-bottom:10px;
      display: flex;
      justify-content: center;
      align-items: center;
      border: 1px solid rgba(153,153,153,0.4);
      .edit-image{
        display: flex;
        position: absolute;
        bottom:0;
        right:0;
        padding: 4px 9px;
        color:#fff;
        font-size: 12px;
        background-color: rgba(0,0,0,0.6);
      };
      .delete-image {
        display: flex;
        position: absolute;
        top:0;
        right:0;
        padding: 3px;
        .el-icon{
          font-size:20px;
        }
      }
    }
    li.imgplus{
      >div{text-align: center;}
      display:flex;
      flex-direction:column;
      justify-content:center;
      align-items: center;
      width: 160px;
      height: 160px; overflow: hidden;
      background: rgba(222,222,222,0.4); cursor: pointer;
      .el-icon{font-size: 50px;color:#999;}
    }
    li:nth-child(6n){margin-right:0;}
  }
</style>
<style lang="scss">
.fm{
    .el-upload{
      position: relative;
      border-radius: 10px !important;
      overflow: hidden;
      .el-avatar{
        display: block;
        }
        .el-avatar--square{border-radius: 10px;}
        .img-change{
            width: 100%;
            height: 30px;
            line-height: 30px;
            position: absolute;
            bottom:0;
            background-color: rgba(0,0,0,0.6);
            text-align: center;
            color: #fff;
        }
    }
}
</style>
